import axios from 'axios';
import config from './config';
import router from '../router';
import { ElMessage } from 'element-plus';
import i18n from '@/i18n';
const { t } = i18n.global;

export default function request(options){
  return new Promise((resolve, reject) => {
    const instance = axios.create({...config});
    instance.interceptors.request.use(
      (config) => {
        let token = localStorage.getItem('pm_token');
        if(token){
          config.headers.token = token;
        } else {
          router.push('/login');
        }
        return config;
      },
      (error) => {
        console.log('request:', error);
        if(error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1){
          ElMessage({ message: '请求超时', type: 'error', showClose: true });
        }
        return Promise.reject(error);
      }
    );

    instance.interceptors.response.use(
      (response) => {
        return response.data;
      },
      (err) => {
        const codeMap = {
          '400': '请求错误',
          '401': '未授权，请登录',
          '403': '拒绝访问',
          '404': '请求地址出错',
          '408': '请求超时',
          '500': '服务器哪部错误',
          '501': '服务未实现',
          '502': '网关错误',
          '503': '服务不可用',
          '504': '网关超时',
          '505': 'HTTP版本不受支持'
        }
        if(err && err.response){
          const status = err.response.status;
          const errMsg = codeMap[status] || '';
          ElMessage({type:'error', message: errMsg, showClose: true});
        }
        return Promise.reject(err);
      }
    );

    instance(options).then((res) => {
      if(res.code === 200 ){
        resolve(res);
      }
      else{
        if(res.code === -2 ){
          router.push('/login');
        }
        ElMessage({type: 'error', message: res.msg || '操作失败', showClose: true});
        reject(res);
      }
    })
    .catch((error) => {
      console.log('has error');
      reject(error);
    });

  });
};

